<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>
<head>
<title>Shop-Locator - MDIS Projekt 4</title>
<meta name="viewport"
	content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;" />

<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple.mobile-web-app-status-bar-style" content="black" />

<link rel="apple-touch-icon" href="apple-touch-icon-iphone.png" /> 
<link rel="apple-touch-icon" sizes="72x72" href="apple-touch-icon-ipad.png" /> 
<link rel="apple-touch-icon" sizes="114x114" href="apple-touch-icon-iphone4.png" />
<link rel="apple-touch-icon" sizes="144x144" href="apple-touch-icon-ipad3.png" />


<link rel="stylesheet" href="iui/iui.css" type="text/css" />
<link rel="stylesheet" href="iui/t/ipdc/ipdc-theme.css" type="text/css" />
<link rel="stylesheet" href="stylesheet.css" />

<script type="application/x-javascript" src="iui/iui.js"></script>

<script type="application/x-javascript"
	src="http://maps.google.com/maps/api/js?sensor=false&region=DE"></script>

<!-- GeoLocation -->
<script type="application/x-javascript">
			var geocoder;
			var map;
			var xml;
			var umkreis;
			var currentMarker, shopMarker;
			var directionsDisplay;
			var directionsService = new google.maps.DirectionsService();

			
			function init() {
				if (navigator.geolocation) {
					document.getElementById('pos-ermitteln').visibility = 'visible';
				} else {
					document.getElementById('pos-ermitteln').visibility = 'hidden';
				}
				geocoder = new google.maps.Geocoder();
				var myOptions = {
						mapTypeId: google.maps.MapTypeId.ROADMAP,
						zoom:7
				}
				directionsDisplay = new google.maps.DirectionsRenderer();
				if(map == null)
					map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
				directionsDisplay.setMap(map);

			}
			
			function getPos() {
				navigator.geolocation.getCurrentPosition(success, error);
			}
			
			function success(position) {
				document.getElementById('location').value = position.coords.latitude + ',' + position.coords.longitude;
				var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
				geocoder.geocode({'latLng' : latlng}, geocodeCallback);
			}
			
			function geocodeCallback(results, status) {
				if (status == google.maps.GeocoderStatus.OK) {
					if (results[0]) {
						for (var comp = 0; comp < results[0].address_components.length; comp++) {
							if (results[0].address_components[comp].types[0] == 'locality') {
								document.getElementById('city').value = results[0].address_components[comp].short_name;
							}
							if (results[0].address_components[comp].types[0] == 'postal_code') {
								document.getElementById('zip').value = results[0].address_components[comp].short_name;
							}
						}
					}
				} else {
					alert("Geocoder failed due to: " + status);
				}
			}
			
			function error(msg) {
				alert("Position konnte leider nicht bestimmt werden.");
			}
/* AJAX STUFF */
			
			function getXMLObject() //XML OBJECT
			{
				var xmlHttp = false;
				try {
					xmlHttp = new ActiveXObject("Msxml2.XMLHTTP") // For Old Microsoft Browsers
				} catch (e) {
					try {
						xmlHttp = new ActiveXObject("Microsoft.XMLHTTP") // For Microsoft IE 6.0+
					} catch (e2) {
						xmlHttp = false // No Browser accepts the XMLHTTP Object then false
					}
				}
				if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
					xmlHttp = new XMLHttpRequest(); //For Mozilla, Opera Browsers
				}
				return xmlHttp; // Mandatory Statement returning the ajax object created
			}
			
			var xmlhttp = new getXMLObject(); //xmlhttp holds the ajax object
			
			function ajaxFunction() {
				if (xmlhttp) {
					var content = "location="
					+ document.getElementById('location').value; //Posting locatiom to Servlet
					content += "&zip=" + document.getElementById('zip').value; //Posting zip to Servlet
					content += "&city=" + document.getElementById('city').value; //Posting city to Servlet
					// Article formatieren
					var input = document.getElementById('article');
					input.value = input.value.substr(0,1).toUpperCase() + input.value.substr(1).toLowerCase();
					content += "&article=" + document.getElementById('article').value; //Posting article to Servlet
					var distance = document.getElementById('distance');
					content += "&distance="
					+ distance.options[distance.selectedIndex].value; //Posting distance to Servlet
					
					xmlhttp.open("POST", "/locator/servlet/shoplocator", true);
					xmlhttp.onreadystatechange = handleServerResponse;
					xmlhttp.setRequestHeader('Content-Type',
											 'application/x-www-form-urlencoded');
					xmlhttp.send(content);
					
					document.getElementById('ergebnisliste').innerHTML = "<img src=spinner_white.gif />";
				}
			}
			
			function handleServerResponse() {
				if (xmlhttp.readyState == 4) {
					if (xmlhttp.status == 200) {
						if(xmlhttp.responseXML != null) {
						document.getElementById('ergebnisliste').innerHTML = "";	
						var del = document.body.getElementsByTagName("div");
						for(a = 0; a < del.length; a++) {
							var id = del[a].getAttribute("id");
							if(id != null && id.substr(0,6) == "detail") {
								document.body.removeChild(del[a]);
							}
						}
						xml = xmlhttp.responseXML.documentElement;
						var x = xml.getElementsByTagName("eintrag");
						for(i = 0; i<x.length;i++) {
							// Ergebnislisteneintrag
							var li = document.createElement("li");
							var a = document.createElement("a");
							a.setAttribute("href", "#detail"+(i+1));
							var cn = x[i].childNodes;
							var name;
							for(j = 0; j<cn.length; j++) {
								if(cn[j].tagName == "name")
									name = cn[j].childNodes[0].nodeValue;
							}
							var txt = document.createTextNode(name+" - "+x[i].getElementsByTagName("distance")[0].firstChild.firstChild.nodeValue);
							a.appendChild(txt);
							li.appendChild(a);
							document.getElementById('ergebnisliste').appendChild(li);
							
							// Detailseite
							main = document.createElement("div");
							main.setAttribute("id", "detail" + (i+1));
							main.setAttribute("title", name);
							main.setAttribute("class", "panel");
							
							// Adresse
							var html = "<fieldset><div class=\"row\"><p>"+name+ "<br />"+ x[i].getElementsByTagName("address")[0].firstChild.nodeValue + "<br />"+ x[i].getElementsByTagName("zip")[0].firstChild.nodeValue + " " + x[i].getElementsByTagName("city")[0].firstChild.nodeValue + "<br />Entfernung: "+ x[i].getElementsByTagName("distance")[0].firstChild.firstChild.nodeValue + "</p></div></fieldset>"
							main.innerHTML = main.innerHTML + html;
							
							// MAP
							html = "<fieldset><div class=\"row\"><label><a href=\"#map_canvas\" onclick=\"setupKarte('"+name+"','"+x[i].getElementsByTagName("location")[0].firstChild.nodeValue+"')\">Zeige Karte</a></label></div></fieldset>"
							main.innerHTML = main.innerHTML + html; //Mit Map ersetzen
							
							// Artikel
							var arts = x[i].getElementsByTagName("article");
							//gesuchter Artikel
							html = "<fieldset>";
							for(k = 0; k < arts.length; k++) {
								if(arts[k].getElementsByTagName("name")[0].firstChild.nodeValue == document.getElementById('article').value) {
								html = html + "<div class=\"row\"><p>";
								html = html + "<label>"+arts[k].getElementsByTagName("name")[0].firstChild.nodeValue + "</label><br /><span> " + arts[k].getElementsByTagName("price")[0].firstChild.nodeValue + " EUR (" + arts[k].getElementsByTagName("stock")[0].firstChild.nodeValue + " verf&uuml;gbar)</span>";
								html = html + "</p></div>";
								}
							}
							html = html + "</fieldset>";
							html = html + "<h2>weitere Artikel</h2>";
							html = html + "<fieldset>";
							for(l = 0; l < arts.length; l++) {
								if(arts[l].getElementsByTagName("name")[0].firstChild.nodeValue != document.getElementById('article').value) {
								html = html + "<div class=\"row\"><p>";
								html = html + "<label>"+arts[l].getElementsByTagName("name")[0].firstChild.nodeValue + "</label><br /><span>" + arts[l].getElementsByTagName("price")[0].firstChild.nodeValue + " EUR (" + arts[l].getElementsByTagName("stock")[0].firstChild.nodeValue + " verf&uuml;gbar)</span>";
								html = html + "</p></div>";
								}
							}
							html = html + "</fieldset>";
							main.innerHTML = main.innerHTML + html;
							
							// in HTML-DOM einhaengen
							document.body.appendChild(main); 
							
						}
						
						} else {
							document.getElementById('ergebnisliste').innerHTML = xmlhttp.responseText;
						}
					} else {
						document.getElementById('ergebnisliste').innerHTML = "";
						alert("Error during AJAX call. Please try again. Statuscode: "
							  + xmlhttp.status);
					}
				}
			}
			
			function setupKarte(name, location) {
				
				var currloc = xml.getElementsByTagName("currentlocation")[0].firstChild.nodeValue.split(",");
				var sloc = location.split(",")
				var currentLoc = new google.maps.LatLng(currloc[0],currloc[1]);
				var shopLoc = new google.maps.LatLng(sloc[0],sloc[1]);
				
					var request = {
					    origin:currentLoc,
					    destination:shopLoc,
					    travelMode: google.maps.TravelMode.DRIVING
					};
					directionsService.route(request, function(result, status) {
					    if (status == google.maps.DirectionsStatus.OK) {
					      directionsDisplay.setDirections(result);
					      var bounds = result.routes[0].bounds;
					        map.fitBounds(bounds);
					        map.setCenter(bounds.getCenter());
						    google.maps.event.trigger(map, 'resize');
					    } 
					    else { 
					    	alert(status);
					    }
					    
					  });
			}
		</script>

<!-- Input etc -->
<script type="application/x-javascript">
			function deleteLoc() {
				document.getElementById("location").value = "";
			}
		</script>

</head>

<body onload="init();">

	<!-- Toolbar -->
	<div class="toolbar">
		<h1 id="pageTitle"></h1>
		<a id="backButton" class="button" href="#"></a>
	</div>

	<!-- Locator -->
	<form id="locator" title="Shop Locator" class="panel" action=""
		method="post" selected="true">
		<div id="pos-ermitteln" style="visibility: visible">
			<a class="whiteButton" href="javascript:getPos();">Position
				bestimmen</a>
		</div>

		<fieldset>
			<div class="row">
				<label for="zip">PLZ:</label> <input name="zip" type="text" size="5"
					id="zip" onchange="deleteLoc();" placeholder="Ihre Postleitzahl" />
			</div>
			<div class="row">
				<label for="city">Ort:</label> <input name="city" type="text"
					size="30" id="city" onchange="deleteLoc();" placeholder="Ihr Ort" />
			</div>
			<div class="row">
				<label for="article">Artikel:</label> <input name="article"
					type="text" size="30" id="article" placeholder="gesuchter Artikel" />
			</div>
			<div class="row">
				<label for="distance">Umkreis in km:</label> <select name="distance"
					id="distance">
					<option value="1" selected="selected">1 km</option>
					<option value="5">5 km</option>
					<option value="10">10 km</option>
					<option value="20">20 km</option>
					<option value="50">50 km</option>
					<option value="100">100 km</option>
				</select>
			</div>
		</fieldset>

		<div>
			<input type="hidden" name="location" id="location" /> <a
				class="whiteButton" onclick="ajaxFunction();" href="#ergebnisliste">Abfrage
				starten</a>
		</div>
	</form>

	<!-- Darstellung der Ergebnisse auf naechster Seite -->
	<ul id="ergebnisliste" title="Ergebnis">

	</ul>

	<!-- Darstellung der Details auf naechster Seite -->
	<div id="detailseite"></div>

	<div id="map_canvas"></div>
</body>

</html>